package com.joolun.framework.web.service;
import com.joolun.common.constant.Constants;
import com.joolun.common.core.domain.entity.SysUser;
import com.joolun.common.core.domain.model.LoginUser;
import com.joolun.common.core.redis.RedisCache;
import com.joolun.common.exception.CustomException;
import com.joolun.common.exception.user.CaptchaException;
import com.joolun.common.exception.user.CaptchaExpireException;
import com.joolun.common.exception.user.UserPasswordNotMatchException;
import com.joolun.common.utils.MessageUtils;
import com.joolun.common.utils.StringUtils;
import com.joolun.framework.manager.AsyncManager;
import com.joolun.framework.manager.factory.AsyncFactory;
import com.joolun.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 登录校验方法
 * 
 * @author ruoyi
 */
@Component
public class SysLoginService
{
    private static final Logger log = LoggerFactory.getLogger(SysLoginService.class);


    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;


    @Autowired
    private ISysUserService userService;

    /**
     * 登录验证
     *  如果账号不存在，但是首页登陆，则报未知错误。解决这个问题，需要前端设置的登陆类型的参数。
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid)
    {

        String telCode = redisCache.getCacheObject(Constants.TEL_CODE_KEY + username);

        if(StringUtils.isNotNull(telCode)){
            SysUser user = userService.selectUserByPhonenumber(username);

            /*if(StringUtils.isNull(user)){
                log.info("登录用户：{} 未注册，请联系管理员.", username);
                throw new BaseException("请联系管理员：" + username );
            }*/
            //如果系统中不存在这个用户，那么，自动生成用户。
            if(StringUtils.isNull(user)){
                SysUser sysUser = new SysUser();
                sysUser.setPhonenumber(username);
                userService.insertDefaultTelUser(sysUser);
                user = userService.selectUserByPhonenumber(username);
            }


//            password = SecurityUtils.encryptPassword(telCode);
            username = user.getUserName();
        }


        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);



        if (captcha == null)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }
        // 用户验证
        Authentication authentication = null;
        try
        {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new CustomException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成token
        return tokenService.createToken(loginUser);
    }




}
